import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/collect_dao.dart';
import 'package:changxindianzishangwu/provider/currentMessageList.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_callback.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

import '../get_contacts_widget.dart';
import 'message_body_widget.dart';

class SelectMessageWidget extends StatefulWidget {
  String conversationID;
  String nickName;
  SelectMessageWidget(this.conversationID, this.nickName, {Key key})
      : super(key: key);

  @override
  _SelectMessageWidgetState createState() => _SelectMessageWidgetState();
}

class _SelectMessageWidgetState extends State<SelectMessageWidget> {
  /// 会话实体
  V2TimConversation _conversation;
  int type = 1;
  String lastMessageId = '';
  String userID = '';
  String groupID = '';
  List<V2TimMessage> someMessage = [];

  /// 消息列表
  List<V2TimMessage> _messages = [];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getConversion();
  }

  Icon righTopIcon = Icon(Icons.add);
  bool isreverse = true;

  //获取会话列表
  _getConversion() async {
    V2TimValueCallback<V2TimConversation> data = await TencentImSDKPlugin
        .v2TIMManager
        .getConversationManager()
        .getConversation(conversationID: widget.conversationID);
    String _msgID;
    int _type = 0;
    String _groupID = '';
    String _userID = '';

    if (data.code == 0) {
      if (data.data.lastMessage != null) {
        _msgID = data.data.lastMessage.msgID;
      }
      _type = data.data.type;
      // _groupID = data.data!.groupID!;
      _userID = data.data.userID;
      _conversation = data.data;
      print("_type: ${_type}");
      print('_userID: ${_userID}');
      print('_groupID: ${_groupID}');

      setState(() {
        type = _type;
        lastMessageId = _msgID;
        groupID = _groupID;
        userID = _userID;
        righTopIcon = _type == 1
            ? Icon(
                Icons.more_vert_rounded,
                color: Colors.black,
              )
            : Icon(
                Icons.supervisor_account,
                color: Colors.lightBlue,
              );
      });
    }

    //判断会话类型，c2c or group

    if (_type == 1) {
      // c2c
      TencentImSDKPlugin.v2TIMManager
          .getMessageManager()
          .getC2CHistoryMessageList(
            userID: _userID,
            count: 100,
          )
          .then((listRes) {
        if (listRes.code == 0) {
          listRes.data.forEach((element) {
            print("消息：：：${element.toJson()}");
          });
          List<V2TimMessage> list = listRes.data;
          if (list == null || list.length == 0) {
            print('没有消息啊！！！');
            list = new List.empty();
          }
          print(
              "conversationID $widget.conversationID 消息数量 ${listRes.data.length}");
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .addMessage(widget.conversationID, list);

          Map<String, List<V2TimMessage>> _messageMap =
              Provider.of<CurrentMessageListModel>(context, listen: false)
                  .messageMap;
          setState(() {
            _messages = _messageMap[widget.conversationID];
          });
        } else {
          print('conversationID 获取历史消息失败 ${listRes.desc}');
        }
      });
    } else if (_type == 2) {
      // group
      TencentImSDKPlugin.v2TIMManager
          .getMessageManager()
          .getGroupHistoryMessageList(
            groupID: _groupID,
            count: 10000,
          )
          .then((listRes) {
        if (listRes.code == 0) {
          print(
              "conversationID listRes.data ${listRes.data.length} $_groupID ");
          List<V2TimMessage> list = listRes.data;
          if (list == null || list.length == 0) {
            print('conversationID 没有消息啊！！！');
            list = new List.empty();
          } else {
            Provider.of<CurrentMessageListModel>(context, listen: false)
                .addMessage(widget.conversationID, list);
            Map<String, List<V2TimMessage>> _messageMap =
                Provider.of<CurrentMessageListModel>(context, listen: false)
                    .messageMap;
            setState(() {
              _messages = _messageMap[widget.conversationID];
            });
          }
          print(
              "conversationID ${widget.conversationID} 消息数量 ${listRes.data.length}");
        } else {
          print('conversationID 获取历史消息失败');
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          elevation: 0.5,
          title: Text(widget.nickName ?? "加载中..."),
          leading: InkWell(
            onTap: () {
              Get.back();
              _messages.forEach((element) async {
                await TencentImSDKPlugin.v2TIMManager.v2TIMMessageManager
                    .setLocalCustomInt(msgID: element.msgID, localCustomInt: 0);
              });
            },
            child: Container(
              alignment: Alignment.center,
              child: Text(
                "取消",
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: sp(15)),
              ),
            ),
          ),
        ),
        body: Container(
          color: ZdColor.rgba(237, 237, 237, 1),
          child: Column(
            children: [
              Container(
                child: Expanded(
                  child: Container(
                    decoration: BoxDecoration(
                      image: DecorationImage(
                          //TODO 背景图 服务器获取
                          image: CachedNetworkImageProvider(
                            getIMBgImg() == "" ? "" : getIMBgImg(),
                          ),
                          fit: BoxFit.fitWidth),
                    ),
                    child: MessageBodyWidget(
                      widget.conversationID,
                      type,
                      userID,
                      groupID,
                      _conversation,
                      messages: _messages,
                      checkMessage: true,
                    ),
                  ),
                ),
              ),
              Container(
                color: Colors.white,
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(
                        child: Container(
                          padding: EdgeInsets.only(left: 50),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              InkWell(
                                onTap: () async {
                                  List list = [];
                                  _messages.forEach((element) {
                                    if (element.localCustomInt == 6) {
                                      someMessage.add(element);
                                    }
                                  });

                                  if (someMessage.length > 0) {
                                    someMessage.forEach((element) async {
                                      if (element.elemType == 1) {
                                        list.add(json.encode({
                                          "msgId": element.msgID,
                                          "roomJid": "0",
                                          "type": "5",
                                          "msg": element.textElem.text
                                        }));
                                      } else if (element.elemType == 3) {
                                        //图片
                                        list.add(json.encode({
                                          "msgId": element.msgID,
                                          "roomJid": "1",
                                          "type": "1",
                                          "url": element
                                              .imageElem.imageList[0].url,
                                          "msg":
                                              element.imageElem.imageList[0].url
                                        }));
                                      } else if (element.elemType == 4) {
                                        //音频
                                        list.add(json.encode({
                                          "msgId": element.msgID,
                                          "roomJid": "1",
                                          "type": "4",
                                          "url": element.soundElem.url,
                                          "msg": element.soundElem.url,
                                          "fileLength": element
                                              .soundElem.duration
                                              .toString()
                                        }));
                                      } else if (element.elemType == 5) {
                                        //视频
                                        list.add(json.encode({
                                          "msgId": element.msgID,
                                          "roomJid": "1",
                                          "type": "2",
                                          "url": element.videoElem.snapshotUrl,
                                          "msg": element.videoElem.videoUrl,
                                          "fileLength": element
                                              .videoElem.duration
                                              .toString()
                                        }));

                                        json.encode(list);
                                      }
                                    });
                                    await CollectDao.addCollect("", "", "",
                                        roomJid: "", emoji: list.toString());
                                  } else {
                                    showToast("至少要选中一条消息");
                                  }
                                },
                                child: Container(
                                    width: width(100),
                                    height: 40,
                                    decoration: BoxDecoration(
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(6)),
                                      color: Colors.white,
                                    ),
                                    child: Text(
                                      "收藏",
                                      style: TextStyle(fontSize: sp(15)),
                                    )),
                              ),
                              InkWell(
                                onTap: () {
                                  _messages.forEach((element) {
                                    if (element.localCustomInt == 6) {
                                      someMessage.add(element);
                                    }
                                  });
                                  if (someMessage.length > 0) {
                                    Get.to(GetContactsWidget(
                                            someMessage: someMessage))
                                        .then((value) {
                                      Get.back();
                                      _messages.forEach((element) async {
                                        await TencentImSDKPlugin
                                            .v2TIMManager.v2TIMMessageManager
                                            .setLocalCustomInt(
                                                msgID: element.msgID,
                                                localCustomInt: 0);
                                      });
                                    });
                                  } else {
                                    showToast("至少要选中一条消息");
                                  }
                                },
                                child: Container(
                                    width: width(100),
                                    height: 40,
                                    decoration: BoxDecoration(
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(6)),
                                      color: Colors.white,
                                    ),
                                    child: Text(
                                      "转发",
                                      style: TextStyle(fontSize: sp(15)),
                                    )),
                              ),
                              InkWell(
                                onTap: () {
                                  _messages.forEach((element) {
                                    if (element.localCustomInt == 6) {
                                      someMessage.add(element);
                                    }
                                  });
                                  if (someMessage.length > 0) {
                                    someMessage.forEach((element) {
                                      deleteMessageFromLocalStorage(
                                          element.msgID);
                                    });
                                  } else {
                                    showToast("至少要选中一条消息");
                                  }
                                },
                                child: Container(
                                    width: width(100),
                                    height: 40,
                                    decoration: BoxDecoration(
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(6)),
                                      color: Colors.white,
                                    ),
                                    child: Text(
                                      "删除",
                                      style: TextStyle(fontSize: sp(15)),
                                    )),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Container(
                color: Colors.white,
                height: MediaQuery.of(context).padding.bottom,
              )
            ],
          ),
        ));
  }

  void deleteMessageFromLocalStorage(String msgId) async {
    V2TimCallback res = await TencentImSDKPlugin.v2TIMManager
        .getMessageManager()
        .deleteMessageFromLocalStorage(msgID: msgId);
    if (res.code == 0) {
      showToast("删除成功");

      Provider.of<CurrentMessageListModel>(context, listen: false)
          .deleteMessage(widget.conversationID);
      _getConversion();
      // 刷新数据 _onLoadMessages();
    } else {
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .deleteMessage(widget.conversationID);
      _getConversion();
      //刷新数据 _onLoadMessages();
    }
    print(res.toJson());
  }
}
